package com.oron3.lock;

import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ToggleButton;

import com.ofek.applicationbase.forms.Broadcaster;
import com.ofek.applicationbase.utils.Delegate;
import com.oron3.locker.R;

public class ToolController {
	private final ViewGroup tool;
	private final CompoundButton edit;
	public interface ToolListener {
		public void onEditChecked(boolean b);
		public void onAddClicked();
		public void searchRequested(String query);
	}
	private final Broadcaster<ToolListener> editBroadcaster = new Broadcaster<ToolListener>();
	public ToolController(final ViewGroup tool) {
		this.tool = tool;
		edit = (ToggleButton)tool.findViewById(R.id.edit);
		edit.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
				editBroadcaster.broadcast(new Delegate<ToolListener>() {
					@Override
					public void invoke(final ToolListener t) {
						t.onEditChecked(isChecked);
					}
				});
			}
		});
		final ImageButton add = (ImageButton)tool.findViewById(R.id.add);

		add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				editBroadcaster.broadcast(new Delegate<ToolListener>() {
					@Override
					public void invoke(final ToolListener t) {
						t.onAddClicked();
					}
				});
			}
		});

		//		final SearchView search = (SearchView)tool.findViewById(R.id.searchView1);
		//		search.setIconifiedByDefault(false);
		//		search.setOnQueryTextListener(new OnQueryTextListener() {
		//
		//			@Override
		//			public boolean onQueryTextSubmit(final String query) {
		//				editBroadcaster.broadcast(new Delegate<ToolListener>() {
		//					@Override
		//					public void invoke(final ToolListener t) {
		//						t.searchRequested(query);
		//					}
		//				});
		//				return true;
		//			}
		//
		//			@Override
		//			public boolean onQueryTextChange(final String newText) {
		//				return false;
		//			}
		//		});
	}
	public boolean getEditState() {
		return edit.isChecked();
	}

	public boolean registerToolListener(final ToolListener listener) {
		listener.onEditChecked(getEditState());
		return editBroadcaster.register(listener);
	}
	public boolean registerToolListener(final ToolListener listener,final boolean invokeNow) {
		if (invokeNow) listener.onEditChecked(getEditState());
		return editBroadcaster.register(listener);
	}
	public boolean unregisterToolListener(final ToolListener listener) {
		return editBroadcaster.unregister(listener);
	}
}
